function SVMCreateVOI(varargin)
% Allows batching over subjects / settings
experiment = 'SVM Gijs';
switch experiment
    case 'SVM Gijs' 
        subjects         = {'LD','TA','MJ','MM','TJ','TJFCD','TK'};
    case 'SVM Bham'; 
        subjects         = {'AM','HB','JZ','MJ','MP','MR','RW'};
end

for n=1:length(subjects)
SVMProduceVOI([varargin 'subject' subjects(n) 'experiment' experiment])
end

end

function SVMProduceVOI(varargin)
%% Transforms VTC + VOI to .mat
% .voi from subject/ROI Data map
% .vtc from subject/Corrected Data

% Check to see if BVQXtoolbox is present in path, recompile if it's not working
addpath([pwd '/BVQX tools'])

cfg.timestarted             = datestr(clock,1);
cfg.subject                 = 'LD'; 
cfg.experiment              = 'SVM Bham';
cfg.verbose                 = 0;
cfg.inspectVOIs             = 0; % Start VOI inspection UI

varargin=varargin{1};
if length(varargin) >= 1;
for n=1:2:length(varargin)
    cfg.(varargin{n})=varargin{n+1}; end; 
end;
switch cfg.experiment
    case 'SVM Gijs'
switch cfg.subject
    % Gijs Unwanted/Wanted Subject:
    case 'LD';          cfg.ROIs={'V1','V2','V3','V3A','V4D','V7','VP','MT','AIPS','PIPS','V4V','FEF','SEF'};
    case 'MJ';          cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS','PIPS','FEF','SEF'};
    case 'MM';          cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS','PIPS'};
    case 'TA';          cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS','PIPS'};
    case 'TJ';          cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS','PIPS'};
    case 'TK';          cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS', 'PIPS', 'FEF', 'SEF'};
    case 'TJFCD';       cfg.ROIs={'V1','V2','V3','V3A','V4V','V7','VP','MT','AIPS','PIPS'}; cfg.rotcode=['g','h'];
end
    case 'SVM Bham'
switch cfg.subject
    % SVM Bham subjects:
    case 'AM';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3a', 'V4V', 'V7', 'KO', 'LO', 'pFs', 'MT', 'MST', 'MTplus','AdaptA','AdaptP','AdaptL','MEM','ALTV','ALTA','VIPS','AIPS'};
    case 'HB';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3a', 'V4V', 'V7', 'KO', 'LO', 'pFs', 'MT', 'MST', 'MTplus','AdaptA','AdaptP','MEM','STAB','ALTV','ALTD','ALTA','VIPS','AIPS'};
    case 'JZ';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3a', 'V4V', 'V7', 'KO', 'LO', 'pFs', 'MT', 'MST', 'MTplus','AdaptA','AdaptP','AdaptL','MEM','STAB','ALTV','ALTA','VIPS','AIPS','extra'};
    case 'MJ';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3A', 'V4V', 'V7', 'V8', 'KO', 'IPS', 'MTplus','AdaptA','AdaptL','STAB','ALTV','ALTD','ALTA','VIPS','AIPS'};
    case 'MP';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3A', 'V4V', 'V7', 'KO', 'LO', 'pFs', 'MT', 'MST', 'MTplus','AdaptA','AdaptP','AdaptL','STAB','ALTV','ALTD','ALTA','VIPS','AIPS','extra'};
    case 'MR';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3A', 'V4V', 'V7', 'V8', 'KO', 'IPS', 'MTplus','AdaptL','MEM','ALTV','ALTA','VIPS','AIPS','extra'};
    case 'RW';          cfg.ROIs={'V1', 'V2', 'V3', 'VP', 'V3A', 'V4V', 'V7', 'V8', 'KO', 'IPS', 'MTplus','AdaptA','AdaptP','AdaptL','MEM','STAB','ALTV','ALTD','ALTA','VIPS','AIPS'};
end
end

disp(['Fetching VOI file data for subject: ' cfg.subject]); tic;
VOIData=SVMReadVOI(cfg); toc;

SVMGetVTCDataFromROI(VOIData,cfg);

end

function VOIData=SVMReadVOI(cfg)
%% Open VOI

VOIData.VOIfiles     = dir([cfg.experiment '/' cfg.subject '/ROI Data/*.voi']);
VOIData.noemptylines1= 4;
VOIData.AllVOIs.xyz  = [];
VOIData.names        = [];
counter              = 1;

for n = 1:length(VOIData.VOIfiles);
disp (['Importing VOIs from file: ' VOIData.VOIfiles(n).name]);

voi{n}  = BVQXfile([cfg.experiment '/' cfg.subject '/ROI Data/' VOIData.VOIfiles(n).name]);
VOIData.names   = [VOIData.names; voi{n}.VOINames];

switch voi{n}.ReferenceSpace
    case 'TAL';    disp('-> Converting VOI from TAL to BV space');
    case 'BV';     disp('-> VOI is in BV space');
    otherwise;     error('Reference space not recognized');
end

for m=1:voi{n}.NrOfVOIs
    ROIName  = [];
    for q = 1:length(VOIData.names{counter}); if ~isspace(VOIData.names{counter}(q)); ROIName = [ROIName VOIData.names{counter}(q)]; end; end;% Fairly inefficient way of removing spaces in names
    if isequal(ROIName(end-length(cfg.subject)+1:end),cfg.subject(1:length(cfg.subject))); ROIName=ROIName(1:end-length(cfg.subject)-1);end 
    VOIData.(ROIName).xyz = voi{n}.BVCoords(char(VOIData.names(counter)));
    VOIData.(['AllVOIs']).xyz                 = [VOIData.AllVOIs.xyz; voi{n}.VOI(m).Voxels];
    counter=counter+1;
end
end
end

function SVMGetVTCDataFromROI(VOIData,cfg)
%% Load VTC data
VTCData.dir   = [cfg.experiment '/' cfg.subject '/Corrected Data'];
VTCData.flist = dir([cfg.experiment '/' cfg.subject '/Corrected Data/*.vtc']);

vtclist = cell(1,length(VTCData.flist));
for n=1:length(VTCData.flist); vtclist{n}=char(VTCData.flist(n).name); end
VTCData.noruns = max(size(vtclist));
disp(['Number of VTC Files Found : ' num2str(VTCData.noruns)]);

for i=1:VTCData.noruns;
disp([' -> Opening VTC file ' num2str(i) '   : ' vtclist{i}]); 
VOI.datastruct{i}                 = BVQXfile([VTCData.dir '/' VTCData.flist(i).name]);
end; 

VOI.dim         = size(VOI.datastruct{1}.VTCData);
VOI.fmrmatrix   = zeros(VOI.dim .* [length(VOI.datastruct) 1 1 1]);

for n=1:length(VOI.datastruct)
    VOI.fmrmatrix(VOI.dim(1)*(n-1)+1:VOI.dim(1)*n,:,:,:) = VOI.datastruct{n}.VTCData;
    VOI.datastruct{n}.VTCData = [];
end

disp(['Started processing ROIs for: ' cfg.subject]);

for zz=1:length(cfg.ROIs)
ROI=cfg.ROIs{zz};
VOIData.(ROI).dim = VOI.dim;

%% Convert VOI data (256x256x256) to VTC space (matrix dimensions):
VOIData.(ROI).BVvox(:,1) = round((VOIData.(ROI).xyz(:,1)-VOI.datastruct{1}.XStart+1)/VOI.datastruct{1}.Resolution);
VOIData.(ROI).BVvox(:,2) = round((VOIData.(ROI).xyz(:,2)-VOI.datastruct{1}.YStart+1)/VOI.datastruct{1}.Resolution);
VOIData.(ROI).BVvox(:,3) = round((VOIData.(ROI).xyz(:,3)-VOI.datastruct{1}.ZStart+1)/VOI.datastruct{1}.Resolution);
VOIData.(ROI).BVvox      = VOIData.(ROI).BVvox((VOIData.(ROI).BVvox(:,1) <= size(VOI.datastruct{i}.VTCData,2))&(VOIData.(ROI).BVvox(:,2) <= size(VOI.datastruct{i}.VTCData,3))&(VOIData.(ROI).BVvox(:,3) <= size(VOI.datastruct{i}.VTCData,4))&(VOIData.(ROI).BVvox(:,1) > 0)&(VOIData.(ROI).BVvox(:,2) > 0) &(VOIData.(ROI).BVvox(:,3) > 0),:);
VOIData.(ROI).BVvox      = unique(VOIData.(ROI).BVvox,'rows');
VOIData.(ROI).NoBVVox    = size(VOIData.(ROI).BVvox,1);

disp([' -> Processing ' ROI ', Number of Voxels in ROI   : ' num2str(size(VOIData.(ROI).BVvox,1))]);

%% Take only propper voxels
data.(ROI).matrix = zeros(size(VOIData.(ROI).BVvox,1),VOIData.(ROI).dim(1),VTCData.noruns);

matrix.(ROI) = VOI.fmrmatrix();


%% Save

if cfg.verbose == 1
        figure;     
        h1 = imagesc(matrix);
        title(['matrix (normalization: MinusMean = ' num2str(cfg.minusmean) ')']);
end


end

if cfg.inspectVOIs == 1
for yy=1:length(cfg.ROIs)
    VOIUI(VOIData,VOI,cfg.ROIs{yy});
    response = input('Continue (n to stop) ? ','s');
    if isequal(response,'n'); break; end;
end
end

    savename = [cfg.experiment '/' cfg.subject '/SVM Data/' 'TimeCourses_' cfg.subject '-NOSMOOTHING.mat'];

disp(['Saving to file: ' savename]);
[a1,a2,a3]=mkdir([cfg.experiment '/' cfg.subject '/SVM Data/']);
save(savename,'matrix','cfg');


end

function VOIUI(VOIData,VOI,ROI)
%% Starts VOI check
% Quick & Dirty
figure(1)
figpos            = get(gcf,'position');
UIhandles.slider  = uicontrol('Style','Slider','SliderStep',[1 5]/size(VOI.datastruct{1}.VTCData,3),'Min',1,'Max',size(VOI.datastruct{1}.VTCData,3),'Position',[20,5,figpos(3)-20,10],'Value',size(VOI.datastruct{1}.VTCData,3)-10,'Callback',{@VOItest});
UIhandles.slider2 = uicontrol('Style','Slider','SliderStep',[1 5]/size(VOI.datastruct,2),'Min',1,'Max',size(VOI.datastruct,2),'Position',[20,15,figpos(3)-20,10],'Value',1,'Callback',{@VOItest});
VOItest(1,{VOIData,VOI,ROI,UIhandles})
end

function VOItest(source,event)
%% Check is VOI is in the right place
persistent VOIData
persistent VOI
persistent ROI
persistent uihandles

if source == 1
VOIData     = event{1};
VOI         = event{2};
ROI         = char(event(3));
uihandles   = event{4};

VOI.color = round(rand*64);
end
scan =round(get(uihandles.slider2,'value'));
slice=round(get(uihandles.slider,'value'));
subplot(2,1,2);
subplot('position',[0.1,0.1,0.8,0.8]);
im1=squeeze(VOI.datastruct{1}.VTCData(10,:,slice,:));
figure(1)
hold on
imagesc(im1)
matrix = squeeze(zeros(size(VOI.datastruct{1}.VTCData(scan,:,:,:))));
colormap(gray); title([ROI ', scan ' num2str(scan) ', slice ' num2str(slice)]); axis off
for j=1:length(VOIData.(ROI).BVvox); 
matrix(VOIData.(ROI).BVvox(j,1),VOIData.(ROI).BVvox(j,2),VOIData.(ROI).BVvox(j,3))=1; 
end;

temp.image=squeeze(matrix(:,slice,:));
temp.image(temp.image==1)=VOI.color;
temp.im2=image(ind2rgb(temp.image,hsv));
set(temp.im2,'AlphaData',logical(temp.image))
hold off;
end